﻿namespace JoinBox.WPF;

using System;
using Cursor = System.Windows.Input.Cursor;
using Cursors = System.Windows.Input.Cursors;
using Control = System.Windows.Controls.Control;
using DragEventArgs = System.Windows.DragEventArgs;
using RadioButton = System.Windows.Controls.RadioButton;

public class ControlDragDrop
{
    public delegate void DelegateControlDragDrop(object sender, DragEventArgs e);
    readonly DelegateControlDragDrop? _cdd;
    Cursor? _cursor;

    /// <summary>
    /// 将控件设置可拖入输入
    /// </summary>
    /// <param name="control">控件</param>
    /// <param name="cdd">委托</param>
    public ControlDragDrop(Control control, DelegateControlDragDrop cdd)
    {
        if (control == null)
            throw new ArgumentNullException(nameof(control));

        _cdd = cdd ?? throw new ArgumentNullException(nameof(cdd));

        var allowDrop = control.GetType().GetProperty("AllowDrop");
        if (allowDrop is null)
            throw new Exception("此控件不存在AllowDrop属性");

        // 是否用作拖放操作的目标
        control.AllowDrop = true;
        control.DragEnter += DragEnter;
        control.Drop += DragDrop;
    }
    void DragEnter(object sender, DragEventArgs e)
    {
        if (sender is Control rb)
        {
            _cursor = rb.Cursor;
            rb.Cursor = Cursors.Arrow; // 指定鼠标形状(更好看)
        }
    }
    void DragDrop(object sender, DragEventArgs e)
    {
        if (sender is Control rb)// RadioButton
        {
            _cdd?.Invoke(sender, e);
            rb.Cursor = _cursor; // 还原鼠标形状
        }
    }
}
